<template>
  <div class="department-container">
    <div class="page-header">
      <h2>部门管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增部门
        </el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :span="8">
        <el-card class="tree-card">
          <template #header>
            <div class="card-header">
              <span>部门结构</span>
              <el-button type="primary" link @click="refreshDepartmentTree">
                <el-icon><Refresh /></el-icon>刷新
              </el-button>
            </div>
          </template>
          <el-input
            v-model="filterText"
            placeholder="输入关键字进行过滤"
            clearable
            class="filter-input"
          />
          <el-tree
            ref="departmentTreeRef"
            :data="departmentTree"
            :props="defaultProps"
            :filter-node-method="filterNode"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span class="node-actions">
                  <el-button type="primary" link @click.stop="handleAdd(data)">
                    <el-icon><Plus /></el-icon>
                  </el-button>
                  <el-button 
                    type="primary" 
                    link 
                    @click.stop="handleEdit(data)"
                    :disabled="data.id === 1"
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button 
                    type="primary" 
                    link 
                    @click.stop="handleDelete(data)"
                    :disabled="data.id === 1 || data.children?.length > 0"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </span>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 部门详情 -->
      <el-col :span="16">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>{{ currentDepartment ? '部门详情' : '请选择部门' }}</span>
            </div>
          </template>
          
          <div v-if="!currentDepartment" class="empty-tip">
            <el-empty description="请从左侧选择部门或新建部门" />
          </div>
          
          <div v-else class="department-detail">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="部门名称">{{ currentDepartment.name }}</el-descriptions-item>
              <el-descriptions-item label="部门编码">{{ currentDepartment.code }}</el-descriptions-item>
              <el-descriptions-item label="上级部门">{{ currentDepartment.parentName || '无' }}</el-descriptions-item>
              <el-descriptions-item label="排序">{{ currentDepartment.sort }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="currentDepartment.status === 1 ? 'success' : 'danger'">
                  {{ currentDepartment.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ currentDepartment.createTime }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">{{ currentDepartment.remark || '无' }}</el-descriptions-item>
            </el-descriptions>
            
            <div class="detail-actions">
              <el-button 
                type="primary" 
                @click="handleEdit(currentDepartment)"
                :disabled="currentDepartment.id === 1"
              >
                编辑部门
              </el-button>
              <el-button 
                type="danger" 
                @click="handleDelete(currentDepartment)"
                :disabled="currentDepartment.id === 1 || currentDepartment.children?.length > 0"
              >
                删除部门
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 部门表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增部门' : '编辑部门'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="departmentFormRef"
        :model="departmentForm"
        :rules="departmentFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="上级部门">
          <el-tree-select
            v-model="departmentForm.parentId"
            :data="departmentTree"
            :props="defaultProps"
            check-strictly
            default-expand-all
            node-key="id"
            :render-after-expand="false"
            placeholder="请选择上级部门"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="departmentForm.code" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="departmentForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="departmentForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="departmentForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'

// 表单引用
const departmentFormRef = ref(null)
const departmentTreeRef = ref(null)

// 对话框状态
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'

// 树过滤文本
const filterText = ref('')

// 当前选中的部门
const currentDepartment = ref(null)

// 部门表单
const departmentForm = reactive({
  id: '',
  parentId: 0,
  name: '',
  code: '',
  sort: 0,
  status: 1,
  remark: ''
})

// 表单验证规则
const departmentFormRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入部门编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9]+$/, message: '部门编码只能包含大写字母和数字', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 树配置
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 部门树数据
const departmentTree = ref([
  {
    id: 1,
    name: '总公司',
    code: 'HQ',
    parentId: 0,
    parentName: '',
    sort: 1,
    status: 1,
    createTime: '2025-01-01 00:00:00',
    remark: '公司总部',
    children: [
      {
        id: 2,
        name: '信息技术部',
        code: 'IT',
        parentId: 1,
        parentName: '总公司',
        sort: 1,
        status: 1,
        createTime: '2025-01-01 00:00:00',
        remark: '负责系统开发和维护'
      },
      {
        id: 3,
        name: '运输部',
        code: 'TRANS',
        parentId: 1,
        parentName: '总公司',
        sort: 2,
        status: 1,
        createTime: '2025-01-01 00:00:00',
        remark: '负责运输调度和管理',
        children: [
          {
            id: 6,
            name: '调度组',
            code: 'DISP',
            parentId: 3,
            parentName: '运输部',
            sort: 1,
            status: 1,
            createTime: '2025-01-01 00:00:00',
            remark: '负责车辆调度'
          },
          {
            id: 7,
            name: '车队管理组',
            code: 'FLEET',
            parentId: 3,
            parentName: '运输部',
            sort: 2,
            status: 1,
            createTime: '2025-01-01 00:00:00',
            remark: '负责车队日常管理'
          }
        ]
      },
      {
        id: 4,
        name: '财务部',
        code: 'FIN',
        parentId: 1,
        parentName: '总公司',
        sort: 3,
        status: 1,
        createTime: '2025-01-01 00:00:00',
        remark: '负责财务管理和结算'
      },
      {
        id: 5,
        name: '客服部',
        code: 'CS',
        parentId: 1,
        parentName: '总公司',
        sort: 4,
        status: 1,
        createTime: '2025-01-01 00:00:00',
        remark: '负责客户服务和投诉处理'
      }
    ]
  }
])

// 监听过滤文本变化
watch(filterText, (val) => {
  departmentTreeRef.value?.filter(val)
})

// 树节点过滤方法
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value) || data.code.includes(value)
}

// 刷新部门树
const refreshDepartmentTree = async () => {
  try {
    // 实际项目中应该调用API获取部门树
    // const { data } = await getDepartmentTree()
    // departmentTree.value = data
    
    ElMessage.success('刷新成功')
  } catch (error) {
    console.error('刷新部门树失败:', error)
    ElMessage.error('刷新部门树失败')
  }
}

// 处理节点点击
const handleNodeClick = (data) => {
  currentDepartment.value = data
}

// 新增部门
const handleAdd = (parentNode = null) => {
  dialogType.value = 'add'
  resetDepartmentForm()
  
  if (parentNode) {
    departmentForm.parentId = parentNode.id
  } else {
    departmentForm.parentId = 0
  }
  
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (data) => {
  if (data.id === 1) {
    ElMessage.warning('根部门不允许编辑')
    return
  }
  
  dialogType.value = 'edit'
  resetDepartmentForm()
  
  // 填充表单数据
  departmentForm.id = data.id
  departmentForm.parentId = data.parentId
  departmentForm.name = data.name
  departmentForm.code = data.code
  departmentForm.sort = data.sort
  departmentForm.status = data.status
  departmentForm.remark = data.remark
  
  dialogVisible.value = true
}

// 删除部门
const handleDelete = (data) => {
  if (data.id === 1) {
    ElMessage.warning('根部门不允许删除')
    return
  }
  
  if (data.children && data.children.length > 0) {
    ElMessage.warning('该部门下有子部门，不允许删除')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除部门 "${data.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 实际项目中应该调用API删除部门
        // await deleteDepartment(data.id)
        
        // 更新本地数据
        removeDepartmentFromTree(departmentTree.value, data.id)
        
        if (currentDepartment.value && currentDepartment.value.id === data.id) {
          currentDepartment.value = null
        }
        
        ElMessage.success('删除部门成功')
      } catch (error) {
        console.error('删除部门失败:', error)
        ElMessage.error('删除部门失败')
      }
    })
    .catch(() => {})
}

// 从树中移除部门
const removeDepartmentFromTree = (tree, id) => {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].id === id) {
      tree.splice(i, 1)
      return true
    }
    
    if (tree[i].children && tree[i].children.length > 0) {
      if (removeDepartmentFromTree(tree[i].children, id)) {
        return true
      }
    }
  }
  
  return false
}

// 重置部门表单
const resetDepartmentForm = () => {
  Object.keys(departmentForm).forEach(key => {
    if (key === 'status') {
      departmentForm[key] = 1
    } else if (key === 'sort') {
      departmentForm[key] = 0
    } else if (key === 'parentId') {
      departmentForm[key] = 0
    } else {
      departmentForm[key] = ''
    }
  })
  
  if (departmentFormRef.value) {
    departmentFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!departmentFormRef.value) return
  
  await departmentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 实际项目中应该调用API添加部门
          // const { data } = await addDepartment(departmentForm)
          // 模拟API返回的数据
          const newDepartment = {
            id: Date.now(),
            parentId: departmentForm.parentId,
            name: departmentForm.name,
            code: departmentForm.code,
            sort: departmentForm.sort,
            status: departmentForm.status,
            remark: departmentForm.remark,
            createTime: new Date().toLocaleString(),
            children: []
          }
          
          // 添加到树中
          addDepartmentToTree(departmentTree.value, newDepartment)
          
          ElMessage.success('添加部门成功')
        } else {
          // 实际项目中应该调用API更新部门
          // await updateDepartment(departmentForm)
          
          // 更新树中的部门
          updateDepartmentInTree(departmentTree.value, {
            id: departmentForm.id,
            parentId: departmentForm.parentId,
            name: departmentForm.name,
            code: departmentForm.code,
            sort: departmentForm.sort,
            status: departmentForm.status,
            remark: departmentForm.remark
          })
          
          // 如果当前选中的是被编辑的部门，更新当前部门
          if (currentDepartment.value && currentDepartment.value.id === departmentForm.id) {
            Object.assign(currentDepartment.value, {
              name: departmentForm.name,
              code: departmentForm.code,
              sort: departmentForm.sort,
              status: departmentForm.status,
              remark: departmentForm.remark
            })
          }
          
          ElMessage.success('更新部门成功')
        }
        
        dialogVisible.value = false
        
        // 刷新树
        nextTick(() => {
          departmentTreeRef.value?.filter(filterText.value)
        })
      } catch (error) {
        console.error('保存部门失败:', error)
        ElMessage.error('保存部门失败')
      }
    }
  })
}

// 添加部门到树
const addDepartmentToTree = (tree, department) => {
  if (department.parentId === 0) {
    tree.push(department)
    return
  }
  
  for (const node of tree) {
    if (node.id === department.parentId) {
      if (!node.children) {
        node.children = []
      }
      department.parentName = node.name
      node.children.push(department)
      return
    }
    
    if (node.children && node.children.length > 0) {
      addDepartmentToTree(node.children, department)
    }
  }
}

// 更新树中的部门
const updateDepartmentInTree = (tree, department) => {
  for (const node of tree) {
    if (node.id === department.id) {
      Object.assign(node, department)
      return true
    }
    
    if (node.children && node.children.length > 0) {
      if (updateDepartmentInTree(node.children, department)) {
        return true
      }
    }
  }
  
  return false
}

// 组件挂载时初始化
onMounted(() => {
  // 默认选中第一个部门
  if (departmentTree.value.length > 0) {
    currentDepartment.value = departmentTree.value[0]
  }
})
</script>

<style scoped>
.department-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
}

.tree-card, .detail-card {
  height: calc(100vh - 180px);
  overflow: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-input {
  margin-bottom: 15px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-actions {
  display: none;
}

.custom-tree-node:hover .node-actions {
  display: inline-block;
}

.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.department-detail {
  padding: 20px 0;
}

.detail-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>
